package com.dmall.graph.floodfill;

public class Leetcode200 {

    private int R, C;
    private char[][] grid;
    private boolean[][] visited;

    private int[][] dirs = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};

    public int numIslands(char[][] grid) {
        R = grid.length;
        if (R == 0) {
            return 0;
        }
        C = grid[0].length;
        if (C == 0) {
            return 0;
        }

        this.grid = grid;
        visited = new boolean[R][C];

        int res = 0;
        for (int i = 0; i < R; i++) {
            for (int j = 0; j < C; j++) {
                if (!visited[i][j] && grid[i][j] == '1') {
                    dfs(i, j);
                    res++;
                }
            }
        }
        return res;
    }

    private void dfs(int x, int y) {
        visited[x][y] = true;
        for (int i = 0; i < dirs.length; i++) {
            int nextx = x + dirs[i][0];
            int nexty = y + dirs[i][1];
            if (inArea(nextx, nexty) && !visited[nextx][nexty] && grid[nextx][nexty] == '1') {
                dfs(nextx, nexty);
            }
        }
    }

    private boolean inArea(int x, int y) {
        return x >= 0 && x < R && y >= 0 && y < C;
    }

    public static void main(String[] args) {
        char[][] grid = {
            {'1', '1', '0', '0', '0'},
            {'1', '1', '0', '0', '0'},
            {'0', '0', '1', '0', '0'},
            {'0', '0', '0', '1', '1'}
        };
        Leetcode200 leetcode200 = new Leetcode200();
        System.out.println(leetcode200.numIslands(grid));
    }
}
